<template>
  <div class="class-bbs-container">
    <!-- 顶部标题 -->
    <el-container class="mb-4">
      <el-header class="bg-primary text-white">
        <div class="container mx-auto px-4 py-3">
          <h1 class="text-xl font-bold">班级论坛</h1>
        </div>
      </el-header>
    </el-container>

    <!-- 发帖按钮 -->
    <el-button
      type="primary"
      icon="ElIconEdit"
      @click="openPostDialog"
      class="mb-4"
    >
      发布新帖子
    </el-button>

    <!-- 帖子列表 -->
    <el-card v-for="post in posts" :key="post.id" class="mb-4">
      <template #header>
        <div class="d-flex justify-between items-center">
          <div class="d-flex items-center">
            <!-- <el-avatar :size="36" :src="post.authorAvatar" class="mr-3" /> -->
            <div>
              <h3 class="font-medium">{{ post.title }}</h3>
              <p class="text-gray-500 text-sm">
                作者：{{ post.author }} 
                <!-- | 时间：{{ post.createdAt }} -->
              </p>
            </div>
          </div>
          <div>
            <el-button
              type="text"
              size="small"
              @click="showDetailDialog(post)"
            >
              查看评论 ({{ post.comments.length }})
            </el-button>
          </div>
        </div>
      </template>
      <p class="text-gray-700 line-clamp-2">{{ post.content }}</p>
    </el-card>

    <!-- 发帖对话框 -->
    <el-dialog v-model="showPostDialog" title="发布新帖子" @close="resetForm">
      <el-form :model="form" label-width="80px">
        <el-form-item label="标题">
          <el-input v-model="form.title" placeholder="请输入帖子标题" />
        </el-form-item>
        <el-form-item label="内容">
          <el-input
            v-model="form.content"
            type="textarea"
            :rows="5"
            placeholder="请输入帖子内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showPostDialog = false">取消</el-button>
        <el-button type="primary" @click="handlePost">发布</el-button>
      </template>
    </el-dialog>

    <!-- 帖子详情对话框 -->
    <el-dialog v-model="showDetailDialogVisible" title="帖子详情">
      <div class="p-4">
        <!-- 帖子内容部分 -->
        <div class="mb-6">
          <h2 class="text-xl font-bold mb-2" style="text-align: center;">{{ currentPost.title }}</h2>
          <div class="flex items-center text-sm text-gray-500 mb-3">
            <!-- <el-avatar :size="32" :src="currentPost.authorAvatar" class="mr-2" /> -->
            <span>{{ currentPost.author }}</span>
            <span class="mx-2">•</span>
            <!-- <span>{{ currentPost.createdAt }}</span> -->
          </div>
          <div class="prose max-w-none">
            <p>{{ currentPost.content }}</p>
          </div>
        </div>

        <!-- 评论区 -->
        <div>
          <h3 class="font-bold mb-4">评论区 ({{ currentPost.comments.length }})</h3>
          
          <!-- 评论列表 -->
          <div v-if="currentPost.comments && currentPost.comments.length > 0">
            <div v-for="(comment, commentIndex) in currentPost.comments" :key="comment.id" class="mb-5">
              <!-- 主评论 -->
              <div class="flex items-start">
                <div class="flex-1">
                  <div class="flex flex-wrap items-center mb-1">
                    <span class="font-medium mr-2">{{ comment.author || '匿名用户' }}:</span>
                    <span>{{ comment.content || '暂无内容' }}</span>
                  </div>
                  
                  <!-- 回复按钮 -->
                  <el-button
                    type="text"
                    size="small"
                    @click="toggleReplyForm(commentIndex)"
                    class="text-primary float-right"
                  >
                    回复
                  </el-button>
                </div>
              </div>
              
              <!-- 回复表单 -->
              <div v-if="activeReplyIndex === commentIndex" class="mt-3">
                <el-form :model="replyForm" class="flex items-start">
                  <el-input
                    v-model="replyForm.content"
                    type="textarea"
                    :rows="2"
                    placeholder="请输入回复内容..."
                    class="flex-1 mr-3"
                    :disabled="isReplying"
                  />
                  <el-button
                    type="primary"
                    @click="submitReply(commentIndex)"
                    :disabled="!replyForm.content || isReplying"
                    :loading="isReplying"
                  >
                    发表回复
                  </el-button>
                </el-form>
              </div>
              
              <!-- 子评论区域 -->
              <div v-if="comment.replies && comment.replies.length > 0" class="mt-4 pl-6 border-l-2 border-gray-200">
                <!-- 移除未使用的 replyIndex -->
                <div v-for="reply in comment.replies" :key="reply.id" class="mt-3">
                  <div class="flex flex-wrap items-center">
                    <span class="font-medium mr-2 text-sm">{{ reply.author || '匿名用户' }} 回复:</span>
                    <span>{{ reply.content || '暂无回复' }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 无评论提示 -->
          <div v-else class="text-center py-4 text-gray-500">
            <p>暂无评论，快来发表第一条评论吧！</p>
          </div>

          <!-- 添加评论表单 -->
          <el-form :model="newCommentForm" class="mt-6">
            <el-input
              v-model="newCommentForm.content"
              type="textarea"
              :rows="3"
              placeholder="请输入评论内容..."
              :disabled="isSubmitting"
              class="w-full"
            />
            <el-button
              type="primary"
              @click="handleAddComment"
              :disabled="!newCommentForm.content || isSubmitting"
              :loading="isSubmitting"
              class="float-right mt-3"
            >
              {{ isSubmitting ? '提交中...' : '发表评论' }}
            </el-button>
          </el-form>
        </div>
      </div>
      <template #footer>
        <el-button @click="showDetailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive,onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { useUserStore} from '@/store/user';
import { PostSubmit,getPosts,CommentSubmit,ReplySubmit } from '@/api/student';
// 定义 form 响应式对象
const form = reactive({
  title: '',
  content: ''
});

const userStore = useUserStore();



// 模拟数据
const posts = ref([]);

// 状态管理
const showPostDialog = ref(false);
const showDetailDialogVisible = ref(false);
const currentPost = ref({ comments: [] });
const newCommentForm = reactive({ content: '' });
const replyForm = reactive({ content: '' });
const isSubmitting = ref(false);
const isReplying = ref(false);
const activeReplyIndex = ref(null);
const isLoading = ref(false);
// 打开发帖对话框
const openPostDialog = () => {
  showPostDialog.value = true;
};


// 获取通知列表
const fetchPostsList = async () => {
  isLoading.value = true;
  try {
    const response = await getPosts({
      studentId: userStore.userInfo.studentId,
    });
    if (response.code === 0) {
      posts.value = response.data;
    }
    console.log(response.data);
  } catch (error) {
    console.error('获取通知列表失败:', error);
  } finally {
    isLoading.value = false;
  }
};


// 发布帖子（使用 form 响应式对象）
const handlePost = async () => {
  if (!form.title || !form.content) {
    ElMessage.error('请填写完整帖子信息');
    return;
  }

  // posts.value.unshift({
  //   id: Date.now(),
  //   ...form,
  //   author: '张三',
  //   authorAvatar: 'https://cube.elemecdn.com/3/7c/3ea6beec67c0c29d23fdt1j7fbcd04b8x.png',
  //   createdAt: new Date().toLocaleString(),
  //   comments: []
  // });


  try {

    const postData = {
      ...form,
      studentId: userStore.userInfo.studentId,
      author: userStore.userInfo.username
    };

    const response = await PostSubmit(postData)

    if (response.code === 0) {

      showPostDialog.value = false;
      resetForm();
      ElMessage.success('帖子发布成功');
      fetchPostsList();
    
    } else {
      ElMessage.error(response.data.message || '发布失败，请重试');
    }
  } catch (error) {
    console.error('API请求失败:', error);
    ElMessage.error('网络错误，请检查网络连接');
  } finally {
    showPostDialog.value = false;
    
  }
};
  
  



// 重置表单
const resetForm = () => {
  form.title = '';
  form.content = '';
};

// 查看帖子详情
const showDetailDialog = (post) => {
  currentPost.value = JSON.parse(JSON.stringify(post));
  showDetailDialogVisible.value = true;
  
};

// 添加评论
const handleAddComment = async() => {
  if (!newCommentForm.content) return;
  
  
  try {

    const commentData = {
      postId: currentPost.value.id,
      content: newCommentForm.content,
      studentId: userStore.userInfo.studentId,
      author: userStore.userInfo.username
    };

    const response = await CommentSubmit(commentData)

    if (response.code === 0) {

  newCommentForm.content = '';
  isSubmitting.value = false;

  ElMessage.success('评论发布成功');
  currentPost.value.comments.push(commentData);
  fetchPostsList()
  //刷新评论接口
    
    
    } else {
      ElMessage.error(response.data.message || '发布失败，请重试');
    }
  } catch (error) {
    console.error('API请求失败:', error);
    ElMessage.error('网络错误，请检查网络连接');
  } finally {
    showPostDialog.value = false;
    


}
}

// 切换回复表单显示
const toggleReplyForm = (index) => {
  if (activeReplyIndex.value === index) {
    // 关闭已打开的回复框
    activeReplyIndex.value = null;
    replyForm.content = '';
  } else {
    // 打开新的回复框
    activeReplyIndex.value = index;
  }
};

// 提交回复
const submitReply = async(commentIndex) => {
  if (!replyForm.content) return;
  
  // isReplying.value = true;
  // const newReply = {
  //   id: Date.now(),
  //   content: replyForm.content,
  //   author: '班长-王小明',
  //   createdAt: new Date().toLocaleString()
  // };

  try {

    const replyData = {
      commentId: commentIndex,
      content: replyForm.content,
      studentId: userStore.userInfo.studentId,
      author: userStore.userInfo.username
    };

    const response = await ReplySubmit(replyData)

    if (response.code === 0) {

    activeReplyIndex.value = null;
  replyForm.content = '';
  isReplying.value = false;
    // 添加到当前评论的回复列表
  currentPost.value.comments[commentIndex].replies.push(replyData);
  
  ElMessage.success('回复发布成功');
    
    } else {
      ElMessage.error(response.data.message || '发布失败，请重试');
    }
  } catch (error) {
    console.error('API请求失败:', error);
    ElMessage.error('网络错误，请检查网络连接');
  } finally {
    showPostDialog.value = false;
    


}


  


};

onMounted(() => {

    fetchPostsList();
});
</script>

<style scoped>
.class-bbs-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
 
}

.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.d-flex {
  display: flex;
}

.justify-between {
  justify-content: space-between;
}

.items-center {
  align-items: center;
}

.mb-4 {
  margin-bottom: 16px;
}

.text-primary {
  color: #409eff;
}

.border-l-2 {
  border-left: 2px solid #e5e7eb;
}

.pl-6 {
  padding-left: 1.5rem; /* 24px */
}
</style>